package cn.news.upload.service;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.xh.storageserver.client.ClientConfig;
import com.xh.storageserver.client.FtpClient;
import com.xh.storageserver.client.FtpClientFactory;
import com.xh.storageserver.client.FtpService;
import com.xh.storageserver.client.util.IoUtils;

import cn.news.upload.entities.XhUploadInfo;

@Service
public class UploadService {
	private Logger logger = LoggerFactory.getLogger(UploadService.class);
	private static FtpClient client;

	@Value("${ftp.username}")
	private String userName;

	@Value("${ftp.password}")
	private String password;

	@Value("${ftp.host}")
	private String host;

	@Value("${ftp.port}")
	private int port;

	@Value("${ftp.url.prefix}")
	private String prefixUrl;

	public synchronized String upload(String fileName, InputStream inputStream) throws IOException {
		if (null == inputStream || StringUtils.isEmpty(fileName)) {
			return "";
		}
		FtpService service = getFtpService();
		String url = service.upload(fileName, inputStream);
		IoUtils.close(service);
		return prefixUrl + url;
	}

	private synchronized FtpService getFtpService() throws IOException {
		if (null == client) {
			client = FtpClientFactory.createFtpClient(new ClientConfig(userName, password, host, port));
			logger.info("upload service create success, host=" + host + ", port=" + port);
		}

		return client.getFtpService();
	}

	public void uploadInfo(List<MultipartFile> fileList, XhUploadInfo info) throws Exception {
		if (null == fileList || null == info) {
			return;
		}

		for (int i = 0; i < fileList.size(); i++) {
			MultipartFile file = fileList.get(i);
			String url = upload(file.getOriginalFilename(), file.getInputStream());

			Method method = info.getClass().getMethod("setPic_url" + (i + 1), new Class[] { String.class });
			method.invoke(info, url);
		}
	}
}